<?php

namespace addons\shopro\controller\commission;

use think\Db;
use think\Request;
use app\admin\model\shopro\commission\Order as OrderModel;

class Order extends Commission
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    // 分销动态
    public function index()
    {
        $agentId = $this->service->user->id;

        $type = $this->request->param('type', "all");
        if (!in_array($type, ['all', 'back', 'cancel', 'yes'])) {
            $this->error("");
        }
        $date = $this->request->param('date/a');

        $query = OrderModel
            ::where('agent_id', $agentId)->whereTime('createtime', 'between', $date)
            ->with([
                'buyer' => function ($query) {
                    return $query->field(['avatar', 'nickname']);
                },
                'order',
                'rewards' => function ($query) use ($agentId) {
                    return $query->where('agent_id', $agentId);
                },
                'order_item'
            ])
            ->order('id desc');
        if ($type !== 'all') {
            $query->$type();
        }

        $data = $query->paginate($this->request->param('list_rows', 10));
        $this->success('', $data);
    }

    public function sumCount()
    {

        $agentId = $this->service->user->id;
        $date = $this->request->param('date/a');

        $commission=OrderModel
            ::alias('od')->join('shopro_commission_reward cr','od.id=cr.commission_order_id','left')
            ->where('od.agent_id', $agentId)
            ->where('cr.commission','>',0)
            ->whereTime('od.createtime', 'between', $date)
            ->field('sum(od.number) as total_number,sum(od.amount) as total_amount')
            ->find();

        $range=OrderModel
            ::alias('od')->join('shopro_commission_reward cr','od.id=cr.commission_order_id','left')
            ->where('od.agent_id', $agentId)
            ->whereTime('od.createtime', 'between', $date)
            ->field('sum(od.number) as total_number,sum(od.amount) as total_amount,sum(cr.commission) as total_commission,sum(cr.range) as total_range,sum(cr.equal) as total_equal')
            ->find();

        $agent=Db::name('shopro_commission_agent')->where(['user_id'=>$agentId])->field('today_driect_money,today_team_money,yesday_driect_money,yesday_team_money')->find();

       return $this->success('',['commission'=>$commission,'range'=>$range,'agent'=>$agent]);

    }

}
